package net.app.zoneland.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.app.zoneland.common.core.vo.Result;
import net.app.zoneland.domain.SysRole;
import net.app.zoneland.domain.SysUser;
import net.app.zoneland.domain.SysUserRole;
import net.app.zoneland.platform.mapper.SysUserMapper;
import net.app.zoneland.platform.mapper.SysUserRoleMapper;
import net.app.zoneland.platform.service.ISysUserService;
import net.app.zoneland.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author LENOVO
 * @CreateTime 2020/12/20 12:49
 * @Version: 1.0
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public IPage<SysUser> list(Page<SysUser> page, SysUser sysUser) {
        if(sysUser==null){
            sysUser=new SysUser();
            sysUser.setStatus(0);
        }
        List<SysUser> list = this.baseMapper.list(page, sysUser);
        page.setRecords(list);
        return page;
    }

    @Override
    public IPage<SysUser> queryUserPage(Page<SysUser> page, SysUser sysUser) {
        List<SysUser> sysUsers = this.baseMapper.queryUserPage(page, sysUser);
        sysUsers.stream().forEach(u ->{
            if (u.getRoles()==null || u.getRoles().isEmpty()){
                List<SysRole> role=new ArrayList<>();
                SysRole ro=new SysRole();
                ro.setName("游客");
                ro.setId(3);
                role.add(ro);
                u.setRoles(role);
            }
        });
        page.setRecords(sysUsers);
        return page;
    }

    @Override
    public UserVo findUserByUsername(String username) {
        return this.baseMapper.queryUserInfoByUserName(username);
    }

    @Override
    public Result saveUser(SysUser user,String roleIds) {

        if(user!=null){
            if(user.getNickname()==null || "".equals(user.getNickname())){
                return Result.error("用户名不能为空");
            }

            if(user.getMobile()==null || "".equals(user.getMobile())){
                return Result.error("手机号不能为空");
            }

            String username = user.getUsername();
            if(username==null || "".equals(username)){
                return Result.error("账号不能为空");
            }

            Long id = user.getId();
           // 如果用户不存在则走新增
            if(id!=null && !"".equals(id)){
                this.baseMapper.updateById(user);
                LambdaQueryWrapper<SysUserRole> eq = new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, id);
                sysUserRoleMapper.delete(eq);
                return getResult(roleIds, id);
            }else{
                UserVo userVo = this.baseMapper.queryUserInfoByUserName(username);
                if(userVo!=null && !userVo.equals("")){
                    return Result.error("账号已经存在");
                }
                String encode = passwordEncoder.encode("123456");
                user.setPassword(encode);
                user.setStatus(0);
                user.setDeleted(0);
                this.baseMapper.saveSysUserCallId(user);
                Long userId = user.getId();
                return getResult(roleIds, userId);
            }
        }else {
            return Result.error("参数不能为空");
        }
    }

    private Result getResult(String roleIds, Long id) {
        if(roleIds.contains(",")){
            String[] split = roleIds.split(",");
            for (String roleId : split) {
                SysUserRole uRole=new SysUserRole();
                int parseInt = Integer.parseInt(roleId);
                uRole.setRoleId(parseInt);
                uRole.setUserId(id);
                sysUserRoleMapper.insert(uRole);
            }
        }else{
            SysUserRole uRole=new SysUserRole();
            int parseInt = Integer.parseInt(roleIds);
            uRole.setRoleId(parseInt);
            uRole.setUserId(id);
            sysUserRoleMapper.insert(uRole);
        }
        return Result.success();
    }

    @Override
    public Result delUserById(SysUser user) {
        try {
            this.baseMapper.updateStatusById(user);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.error("删除失败");
    }

    @Override
    public Result changePwd(SysUser user) {
        try {
            String encode = passwordEncoder.encode("123456");
            user.setPassword(encode);
            this.baseMapper.changpwd(user);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.error("操作出错啦！");
    }

    @Override
    public Result updateUser(UserVo user) {
        try {
            this.baseMapper.updateUser(user);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作异常");
        }
        return Result.success();
    }
}
